package ua.com.common.STIntegration;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.InternalResourceView;

import antlr.collections.List;

import com.github.mustachejava.Mustache;

/*import org.stringtemplate.v4.AutoIndentWriter;
import org.stringtemplate.v4.ST;
import org.stringtemplate.v4.STGroup;
*/

public class MustacheBeenView extends InternalResourceView implements InitializingBean{
	
	TemplateMustacheDAO templateDAO;


	private final static String errorPageName = "404";
	
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	protected void renderMergedOutputModel(Map model,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		render(model, request, response,
				getBeanName());
	}
	
	
	
	public void render(Map<String, ?> model,
			HttpServletRequest request,
			HttpServletResponse response, String viewName) throws Exception {
		
		Map<String, Object> params = new HashMap<String, Object>(model);
		
		
		Mustache template = templateDAO.get(viewName);
		if (template==null){
			template = templateDAO.get(errorPageName);
			params.put("missed", viewName);
		} 
		
		PrintWriter writer = response.getWriter();
		System.err.println("params"+params);
		template.execute(writer, model);
		
 		writer.flush();
		writer.close();
	}
	
	@Override
	public void afterPropertiesSet() throws Exception {
		templateDAO = getApplicationContext().getBean(TemplateMustacheDAO.class);
		super.afterPropertiesSet();
	}

}